#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import json
import time
import logging
demo_path = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/json_template/get_demo.json")


class UpdateJson(object):

    def __init__(self, file_path=demo_path, method="get"):
        if method == "get":
            method_json = self.get_file(file_path)
            self.change_dict = json.loads(method_json)

    @staticmethod
    def get_file(file_path):
        try:
            with open(file_path, "rb") as detail:
                file_details = detail.read()

        except IOError:
            logging.error('Input File Not Found')
            exit()
        return file_details

    def update_request_header(self, headers):
        """
        替换请求头
        :param headers: dict
        :return:
        """
        self.change_dict['req']['header'] = headers
        logging.info(self.change_dict)

    def update_url(self, urls):

        """
        修改URL
        :param urls: string
        :return:
        """
        self.change_dict['req']['url'] = urls
        logging.info(self.change_dict)

    def update_request_body(self, req_body):
        """
        修改请求body
        :param req_body: dict
        :return:
        """
        self.change_dict['req']['body'] = req_body
        logging.info(self.change_dict)

    def update_net(self, src_ip=None, src_port=None, dst_ip=None, dst_port=None):
        """
        修改五元组
        :param src_ip:
        :param src_port:
        :param dst_ip:
        :param dst_port:
        :return:
        """
        if src_ip is not None:
            self.change_dict['net']['src_ip'] = src_ip
        if src_port is not None:
            self.change_dict['net']['src_port'] = src_port
        if dst_ip is not None:
            self.change_dict['net']['dst_ip'] = dst_ip
        if dst_port is not None:
            self.change_dict['net']['dst_port'] = dst_port

    def update_time(self, tm=None):
        if tm is None:
            self.change_dict['meta']['tm'] = time.time()
        else :
            self.change_dict['meta']['tm'] = tm

    def update_response_header(self, headers):
        """
        替换返回头
        :param headers: dict
        :return:
        """
        self.change_dict['rsp']['header'] = headers
        logging.info(self.change_dict)

    def update_response_body(self, rsp_body):
        """
        修改返回body
        :param req_body: dict
        :return:
        """
        self.change_dict['rsp']['body'] = rsp_body
        logging.info(self.change_dict)

    def update_status(self, status):
        self.change_dict['rsp']['status'] = status